package com.fanxuankai.boot.upush;

import com.alibaba.fastjson.JSON;
import com.fanxuankai.boot.upush.autoconfigure.PushProperties;
import com.fanxuankai.boot.upush.constant.PushConstants;
import com.fanxuankai.boot.upush.model.Msg;
import com.fanxuankai.boot.upush.model.Result;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;

/**
 * @author fanxuankai
 */
@Component
public class PushClient {
    private final PushProperties properties;
    private final RestTemplate restTemplate;
    private static final Logger LOGGER = LoggerFactory.getLogger(PushClient.class);

    public PushClient(PushProperties properties, RestTemplate restTemplate) {
        this.properties = properties;
        this.restTemplate = restTemplate;
    }

    /**
     * 推送
     * @param msg /
     * @return Result
     */
    public boolean send(Msg msg) {
        Result result = doSend(msg);
        if (result == null) {
            return false;
        }
        if (PushConstants.RET_SUCCESS.equals(result.getRet())) {
            return true;
        }
        LOGGER.error("推送失败: {}", result);
        return false;
    }

    /**
     * 推送
     * @param msg /
     * @return Result
     */
    public Result doSend(Msg msg) {
        String timestamp = Integer.toString((int) (System.currentTimeMillis() / 1000));
        msg.setTimestamp(timestamp);
        msg.setAppKey(properties.getAppKey());
        String url = properties.getUrl();
        String postBody = JSON.toJSONString(msg);
        String sign =
                DigestUtils.md5Hex(("POST" + url + postBody + properties.getAppMasterSecret()).getBytes(StandardCharsets.UTF_8));
        url = url + "?sign=" + sign;
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> entity = new HttpEntity<>(postBody, headers);
        String json = restTemplate.postForObject(url, entity, String.class);
        if (StringUtils.isEmpty(json)) {
            return null;
        }
        return JSON.parseObject(json, Result.class);
    }
}
